import StorageUtils from "../utils/StorageUtils";
import CacheConfig from "../config/CacheConfig";
import WXUtils from "../utils/WXUtils.js";
import LogService from "../service/LogService.js";
import request from '@/utils/request'
import requestUser from '@/utils/request/index4.js'
import {
	showInfo
} from "../utils/ToastUtils";
import {
	showError
} from "../core/app";
import {
	login
} from "../api/login";
import {
	info
} from "../api/user.js";
import Config from '@/core/config'
const apiUrl = Config.get('apiUrl4')

class UserService {


	constructor() {
		this.userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
		console.log("this.userInfo", this.userInfo);
	}

	async isLogin() {
		const token = StorageUtils.get(CacheConfig.TOKEN_KEY);
		return !!token;
	}

	async wxLogin() {
		const {
			code
		} = await WXUtils.login();
		this.code = code;
		return await this.login(code);
	}

	async login(code) {
		try {
			// 2 获取小程序登录成功后的code
			// #ifdef MP-WEIXIN
			const oauth = {
				client_id: "ox",
				client_secret: "123456",
				grant_type: "password",
				scope: "all",
				appid: 'wx9defdd2125f88fbb'
			}
			const loginParams = {
				code,
				...oauth
			};
			const {access_token} = await login(loginParams);
			// console.log("access_token", access_token);
			// #endif
			
			//  把token存入缓存中
			await StorageUtils.save(CacheConfig.TOKEN_KEY, access_token);
			// StorageUtils.remove(CacheConfig.USER_INFO_KEY);
			// #ifdef MP-WEIXIN
			await this.getUserInfo();
			// #endif
			showInfo("授权成功");
			return true;
		} catch (error) {
			console.log(error);
			showError("授权失败, 请重试");
		}

		return false;
	}

	updateInfo(v) {
		let response;
		uni.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: async (res) => {
				LogService.debug("getUserProfile", res);
				let {
					rawData,
					signature,
					iv,
					encryptedData
				} = res;
				const params = {
					rawData,
					signature,
					iv,
					encryptedData,
					appid: 'wx9defdd2125f88fbb',
					...v
				};

				response = await requestUser.put("user/info", params, '');
				LogService.debug("updateInfo", response);
				this.userInfo = response;
				StorageUtils.save(CacheConfig.USER_INFO_KEY, this.userInfo);
			}
		})
	}

	async getUserInfo(flag) {
		this.userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
		if (!this.userInfo || !!flag) {
			// 获取详细个人信息
			const userInfoRes = await info({
				'access_token': StorageUtils.get(CacheConfig.TOKEN_KEY)
			});
			console.log("userInfoRes", userInfoRes);
			this.userInfo = userInfoRes.obj;
			console.log("getUserInfo", this.userInfo);
			if (!!this.userInfo.mobile) {
				StorageUtils.save(CacheConfig.USER_INFO_KEY, this.userInfo);
			}
		}
		return this.userInfo;
	}

	/**
	 * detail:
	 cloudID: "55_txtozyCJh0U4y2-l_ls3KvKLF2o-YW3h248n4NJwCTTO46qKxj_mIGG4BTQ"
	 encryptedData: "TH8KcGyF/OTK/0BA97M5oNKqUp9pEreIiFEGOERMQwKgKm5mldemHlKUQECB2WdnWruFCMk2gHYf2RvbT7tVtqopOW9dMiNZvhKkV0muKVtu8v7WtE3kyAed5ZV6A7mnZUCcZ1Bl/1+pMF6rZsqRgVTfSiSWt7KcaOgGr7LGYP+FZYHzusi30SmYdWkVhkkvXF5r9NKCoRY9McpkmH8jSA=="
	 errMsg: "getPhoneNumber:ok"
	 iv: "lTP6P+ZHPQoedQ+v+l4f0g=="
	 * @param detail
	 * @returns {Promise<void>}
	 */
	async updatePhone(detail) {
		let {
			iv,
			encryptedData
		} = detail;
		const params = {
			iv,
			encryptedData
		};

		try {
			await request({
				url: "/user/bindPhone",
				data: params,
				auth: true,
				method: "put"
			});
			// Taro.removeStorageSync(CacheConfig.USER_INFO_KEY);
			await this.getUserInfo(true);
		} catch (e) {
			LogService.error(e);
		}
	}

}

export default new UserService();